<?php
/**
 * Description of SQLManager
 *
 * @author Lukas
 */
class SQLManager {

    private $katalog = "";
    private $fileName = "";
    private $preparedQuery = "";

    public function __construct( $SQLName,$modul="" ) {
            $this->fileName = $SQLName.".sql";

            if($modul != "")
                $this->katalog = 'Modules/'.$modul."/SQL/";
             else
                $this->katalog = "SQL/";

            $head = Application::getSitePath();
            if( !file_exists( $head.$this->katalog.$this->fileName ) ) {
                throw new Exception( "Nie można odnaleźć pliku zapytania: ".$head.$this->katalog.$this->fileName ."." );
            } else {
                    $uchwyt = @fopen($head.$this->katalog.$this->fileName, "r");
                    $this->preparedQuery = @fread($uchwyt, @filesize( $head.$this->katalog.$this->fileName ) );
            }
    }

    public function setInt( $numer, $parametr ){
        $this->preparedQuery = str_replace( ":".$numer.":", $parametr, $this->preparedQuery );
    }

    public function setString( $numer, $parametr ){
        $this->preparedQuery = str_replace( ":".$numer.":", "'".$parametr."'",$this->preparedQuery );
    }

    public function addAndCondition( $condition ){
        if ( strpos( $this->preparedQuery , "WHERE" ) )
            $this->preparedQuery .= " AND (".$condition.")";
        else
            $this->preparedQuery .= " WHERE (".$condition.")";
    }

    public function addOrCondition( $condition ){
        if ( strpos( $this->preparedQuery , "WHERE" ) )
            $this->preparedQuery .= " OR (".$condition.")";
        else
            $this->preparedQuery .= " WHERE (".$condition.")";
    }

    public function getSQLQuery(){
        return $this->preparedQuery;
    }

    /**
     * Metoda dodająca do zapytania warunek ORDER BY i pola i pożądki względem tablicy tablic.
     *
     * @param array() $warunki Tablica zawierająca tablicę z parami <pole>,<kierunek_porządku>
     */
    public function addOrder( $warunki ){
        $this->preparedQuery .= " ORDER BY";
        foreach($warunki as $klucz => $warunek){
            $this->preparedQuery .= ( $klucz==0 ? "" : ",");
            $this->preparedQuery .= " ".$warunek[0]." ".$warunek[1]."";
        }
    }
}
?>
